import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/config/const.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/pages/others/manager/dialog_manager.dart';
import 'package:inmotion_pro/service/log_service.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../config/theme.dart';
import '../../http/api_helper.dart';
import '../../l10n/local.dart';
import '../login_register/verify_captch/verify_captch_view.dart';
import '../models/user_model.dart';

mixin AccountSecurityMixin {
  // 发送验证码
  Future<bool> accountSecurityRequestVerificationCode({
    required String account,
    required CodePlatform platform,
    required CodeType codeType,
    String? securityToken,
    Map<String, String>? tokenMap,
  }) {
    Loading.showLoading(null);
    return ApiHelper()
        .requestVerificationCode(
      account: account,
      platform: platform,
      codeType: codeType,
      securityToken: securityToken,
      tokenMap: tokenMap,
    )
        .then((codeRsp) {
      if (codeRsp.$1) {
        Loading.showToast(local.send_verification_code_success);
        // 验证成功
        return Future(() => true);
      } else {
        Loading.dismiss();
        // 需要图形验证码
        return _showImageVerifyCodeDialog(
          account: account,
          platform: platform,
          codeType: codeType,
          captchaUrl: codeRsp.$2,
        ).then((rspMap) {
          if (rspMap != null) {
            // 通过图形验证码，则重新发送证码
            return accountSecurityRequestVerificationCode(
              account: account,
              platform: platform,
              codeType: codeType,
              securityToken: securityToken,
              tokenMap: rspMap,
            );
          } else {
            return Future(() => false);
          }
        });
      }
    });
  }

  // 弹出图形验证码
  Future<Map<String, String>?> _showImageVerifyCodeDialog({
    required String account,
    required CodePlatform platform,
    required CodeType codeType,
    required String captchaUrl,
  }) {
    Completer<Map<String, String>?> completer =
        Completer<Map<String, String>?>();
    DialogManager.showSingle(
      tag: DialogTag.VERIFY_CAPTCHA,
      child: Container(
        constraints:
            BoxConstraints(maxHeight: Get.height * 0.8, minHeight: 200),
        color: lxColorScheme.blockColor,
        child: SingleChildScrollView(
          child: VerifyCaptchaView(
            url: captchaUrl,
            webviewHeight: 200.0.obs,
            onSuccess: (token, tokenName) {
              if (token == null || tokenName == null) {
                if (!completer.isCompleted) {
                  completer.complete(null);
                }
              } else {
                if (!completer.isCompleted) {
                  DialogManager.dismiss(tag: DialogTag.VERIFY_CAPTCHA);
                  completer.complete({tokenName: token});
                }
              }
            },
          ),
        ),
      ),
    );
    return completer.future;
  }

  // 第三方登录类型
  void accountSecurity3rdLogin(Auth3rdType auth3rdType,
      {Function(Auth3rdModel)? onSuccess, VoidCallback? onError}) {
    bool isApple = Platform.isIOS ? true : false;
    Loading.showLoading(
        '${StringUtil.capitalizeFirstLetter(auth3rdType.name)} ${local.login_title}');
    // 登陆
    Auth3rdManager(
      auth3rdType,
      GoogleClientIdAndroid,
      GoogleClientIdIOS,
      GoogleServerId,
    ).auth().then((auth3rdModel) {
      LogService.to.info('【$runtimeType】第三方登陆 isApple = $isApple');
      debugPrint('【$runtimeType】第三方登陆：${auth3rdModel.toMap()}');
      // 登录成功回调
      Loading.dismiss();
      if (onSuccess != null) {
        onSuccess(auth3rdModel);
      }
    }).catchError((e) {
      // 登录失败回调
      if (onError != null) {
        onError();
      }
      if (e is AuthException) {
        if (e.code == AuthException.CODE_GOOGLE_NULL_ACCOUNT) {
          LogService.to
              .error('【$runtimeType】Google Account is null-${e.message}');
        } else if (e.code == AuthException.CODE_GOOGLE_AUTH_ERROR) {
          LogService.to.error('【$runtimeType】Google Auth Error: ${e.message}');
        } else if (e.code == AuthException.CODE_GOOGLE_SIGN_IN_ERROR) {
          LogService.to
              .error('【$runtimeType】Google Sign In Error: ${e.message}');
        } else if (e.code == AuthException.CODE_APPLE_SIGN_IN_ERROR) {
          LogService.to
              .error('【$runtimeType】Apple Sign In Error: ${e.message}');
        } else {
          LogService.to.error('【$runtimeType】第三方登陆失败：${e.toString()}');
        }
      } else {
        LogService.to.error('【$runtimeType】第三方登陆失败：${e.toString()}');
      }
      Loading.showToast('${local.login_title} ${local.fail}');
    });
  }
}
